# encoding:utf-8
import requests
import time
import sys
import json

reload(sys)
sys.setdefaultencoding('utf8')

# 此处需要ak，ak申请地址：https://lbs.amap.com/dev/key/app
ak = "vIoIiZKv2BB779ws19O6ininYY7b7R0H"

# 地理信息解析
def amp_geocode(addr):
    addrencode = addr.encode(encoding='utf8')
    url = "http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s&callback=" % (addrencode,ak)
    #print url
    response = requests.get(url)
    if response.status_code == 200:
        try:
            mes_to_dict = json.loads(response._content)
            #print mes_to_dict
            if mes_to_dict['status'] == 0:
                #lat = mes_to_dict['result']['location']['lat']
                #lng = mes_to_dict['result']['location']['lng']
                #precise = mes_to_dict['result']['precise']
                #confidence = mes_to_dict['result']['confidence']
                #comprehension = mes_to_dict['result']['comprehension']
                #level = mes_to_dict['result']['level']
                time.sleep(1)
                #print level
                return mes_to_dict['result']
            else:
                print "地址解析错误，错误码：[%s]" %  mes_to_dict['status']
                time.sleep(1)
                return None
        except Exception as e:
            print("地址解析异常：",e)
            time.sleep(1)
            return None
    else:
        print("接口访问异常：", response.status_code)
        time.sleep(1)
        return None


if __name__ == "__main__":
    print "===================================================================="  
    print "                                 __                                 "
    print "  ____ _____    _____   ____   _/  |_  ____      ____ ______  ______"
    print " /    \\__  \  /     \_/ __ \  \   __\/  _ \    / ___\\____ \/  ___/"
    print "|   |  \/ __ \|  Y Y  \  ___/   |  | (  <_> )  / /_/  >  |_> >___ \ "
    print "|___|  (____  /__|_|  /\___  >  |__|  \____/   \___  /|   __/____  >"
    print "     \/     \/      \/     \/                 /_____/ |__|       \/ "
    print "====================================================================" 
    
    vlen = len(sys.argv)
    if vlen <=1:
        print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , "请输入正确参数，参数格式如下："
        print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , "方法1(返回JSON)：>>> python name2gps.py 要查询的地址"
        print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , "方法2(返回文件)：>>> python name2gps.py 输入文件地址 输出文件地址"
    
    if vlen ==2:
        address = sys.argv[1]
        local = amp_geocode(address)
        print local
    if vlen ==3:
        #读取文件
        vres = []
        infile = sys.argv[1]
        outfile = sys.argv[2]
        with open(infile, 'r') as f:
            addrs = f.readlines()
            #print addrs
        cnt = len(addrs)
        i = 0  
        for address in addrs:
            address = address.rstrip('\n')
            address = address.replace('|',' ')
            print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ,"检索地址开始：",address
            local = amp_geocode(address)
            str = "%s|%s|%s|%s|%s|%s|%s\n" % (address,local['location']['lat'],local['location']['lng'],local['precise'],local['confidence'],local['comprehension'],local['comprehension'])
            print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ,"检索地址完成：",address
            vres.append(str)
        
        with open(outfile,'w') as f:
            f.writelines(vres)
        
        
    #print "北京市西城区红局南街6号院1号楼3单元202:",amp_geocode("北京市西城区红局南街6号院1号楼3单元202")
    #print "辽宁省沈阳市铁西区:",amp_geocode("辽宁省沈阳市铁西区")
    #print "111:",amp_geocode("111")
    
    